package net.zigin.nhi.waste.view.history;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONArray;
import com.gyf.immersionbar.ImmersionBar;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.siberiadante.titlelayoutlib.TitleBarLayout;

import net.zigin.nhi.waste.R;
import net.zigin.nhi.waste.adapter.HistoryAdapter;
import net.zigin.nhi.waste.adapter.IActivityHistoryType;
import net.zigin.nhi.waste.adapter.NoDataAdapter;
import net.zigin.nhi.waste.adapter.NumericWheelAdapter;
import net.zigin.nhi.waste.adapter.ReceiverAdapter;
import net.zigin.nhi.waste.bean.HistoryBean;
import net.zigin.nhi.waste.bean.ReceiverBean;
import net.zigin.nhi.waste.constants.Constants;
import net.zigin.nhi.waste.net.ApiCall;
import net.zigin.nhi.waste.net.BaseResponse;
import net.zigin.nhi.waste.net.HttpRetrofitClient;
import net.zigin.nhi.waste.net.PublicService;
import net.zigin.nhi.waste.utils.DateUtils;
import net.zigin.nhi.waste.utils.StringUtil;
import net.zigin.nhi.waste.view.depotout.OutPrintActivity;
import net.zigin.nhi.waste.view.depotout.ReceiverActivity;
import net.zigin.nhi.waste.view.widget.FilterDialog;
import net.zigin.nhi.waste.view.widget.WheelView;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import io.paperdb.Paper;
import io.reactivex.Observable;

/**
 * 医废追溯界面
 */
public class HistoryActivity extends AppCompatActivity {

    private TitleBarLayout mTitle;
    private LinearLayout mFilter;
    private RecyclerView mRvHistory;
    private LinearLayout mStartLayout;
    private SmartRefreshLayout mRefresh;
    private TextView mStartTime;
    private LinearLayout mEndLayout;
    private TextView mEndTime;

    private Map<String, Object> map = new HashMap<>();
    private List<HistoryBean> historyList = new ArrayList<>();
    private HistoryAdapter adapter;
    private NoDataAdapter noDataAdapter = new NoDataAdapter();

    private int page = 1;
    private int limit = 20;

    private long startT;
    private long endT;
    WheelView year;
    WheelView month;
    WheelView day;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_history);
        initView();
        mRefresh.autoRefresh();
    }

    @Override
    protected void onResume() {
        super.onResume();
        setTime();
        initData();
    }

    private void initView() {
        ImmersionBar.with(this).init();
        mTitle = findViewById(R.id.title);
        mFilter = findViewById(R.id.filter);
        mRvHistory = findViewById(R.id.rv_history);
        mStartLayout = findViewById(R.id.start_layout);
        mStartTime = findViewById(R.id.start_time);
        mEndLayout = findViewById(R.id.end_layout);
        mEndTime = findViewById(R.id.end_time);
        mRefresh = findViewById(R.id.refresh);

        mRvHistory.setLayoutManager(new LinearLayoutManager(this));
    }

    private void initData() {
        //获取筛选对话框中选中项对应的值
        String wasteClassifyCode = Paper.book().read(Constants.WASTE_CLASSIFY_CODE);
        if (StringUtil.isNotEmpty(wasteClassifyCode)) {
            map.put("wasteClassifyCode", wasteClassifyCode);
        }
        String wasteStatus = Paper.book().read(Constants.WASTE_STATUS);
        if (StringUtil.isNotEmpty(wasteStatus)) {
            map.put("status", wasteStatus);
        }
        String hospitalDepartId = Paper.book().read(Constants.HOSPITAL_DEPART_ID);
        if (StringUtil.isNotEmpty(hospitalDepartId)) {
            map.put("hospitalDepartId", hospitalDepartId);
        }

        mRefresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                historyList.clear();
                page = 1;
                map.put("isPage", true);
                map.put("pageIndex", page);
                map.put("pageSize", limit);
                Observable<BaseResponse<String>> observable = HttpRetrofitClient.getInstance().create(PublicService.class)
                        .getHistory(Paper.book().read(Constants.TOKEN), map);
                HttpRetrofitClient.execute(observable, new ApiCall<String>() {
                    @Override
                    protected void success(String data) {
                        if (StringUtil.isNotEmpty(data)) {
                            Log.i("医废追溯", data);
                            historyList = JSONArray.parseArray(data, HistoryBean.class);
                            if (historyList != null && historyList.size() > 0) {
                                adapter = new HistoryAdapter(historyList);
                                mRvHistory.setAdapter(adapter);
                                page++;
                            } else {
                                mRvHistory.setAdapter(noDataAdapter);
                            }
                        } else {
                            mRvHistory.setAdapter(noDataAdapter);
                        }
                        mRefresh.finishRefresh();
                    }

                    @Override
                    public void error(String msg) {
                        super.error(msg);
                        mRefresh.finishRefresh();
                        mRvHistory.setAdapter(noDataAdapter);
                    }
                });
            }
        });

        mRefresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                map.put("isPage", true);
                map.put("pageIndex", page);
                map.put("pageSize", limit);
                Observable<BaseResponse<String>> observable = HttpRetrofitClient.getInstance().create(PublicService.class)
                        .getHistory(Paper.book().read(Constants.TOKEN), map);
                HttpRetrofitClient.execute(observable, new ApiCall<String>() {
                    @Override
                    protected void success(String data) {
                        if (StringUtil.isNotEmpty(data)) {
                            Log.i("医废追溯", data);
                            List<HistoryBean> newList = JSONArray.parseArray(data, HistoryBean.class);
                            if (newList != null && newList.size() > 0) {
                                historyList.addAll(newList);
                                adapter.notifyData(historyList);
                            }
                            if (historyList.size() < limit) {
                                mRefresh.finishLoadMoreWithNoMoreData();
                            } else {
                                mRefresh.finishLoadMore();
                                page++;
                            }
                        } else {
                            mRefresh.finishLoadMoreWithNoMoreData();
                        }
                    }
                });
            }
        });


        mFilter.setOnClickListener(v -> {
            FilterDialog dialog = FilterDialog.getInstance(HistoryActivity.this, HistoryActivity.this, mRvHistory, adapter, map, dd);
            dialog.show();
        });

        mTitle.setRightImageClickListener(v -> {
            Intent intent = new Intent(HistoryActivity.this, ScanRecordActivity.class);
            startActivity(intent);
        });

    }

    /**
     * 接收筛选对话框选择的类型，更新adapter数据源
     */
    private IActivityHistoryType dd = new IActivityHistoryType() {
        @Override
        public void upDataUi(List<HistoryBean> list) {
            if (list != null && list.size() > 0) {
                historyList.clear();
                historyList.addAll(list);
                adapter = new HistoryAdapter(historyList);
                mRvHistory.setAdapter(adapter);
            }
        }
    };

    /**
     * 时间筛选
     */
    private void setTime() {
        DateUtils dateUtils = new DateUtils();
        endT = System.currentTimeMillis() / 1000;
        mEndTime.setText(dateUtils.timeStamp2Date(String.valueOf(endT), "yyyy-MM-dd"));
        mStartTime.setText("请选择开始时间");

        mStartTime.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (StringUtil.isNotEmpty(mStartTime.getText().toString()) && StringUtil.isNotEmpty(mEndTime.getText().toString())) {
                    if (!mStartTime.getText().toString().equals("请选择开始时间")) {
                        startT = dateUtils.getStringToDate(mStartTime.getText().toString(), "yyyy-MM-dd");
                        endT = dateUtils.getStringToDate(mEndTime.getText().toString(), "yyyy-MM-dd");
                        if (startT > endT) {
                            Toast.makeText(getApplicationContext(), "开始时间不能超过结束时间", Toast.LENGTH_SHORT).show();
                        } else if (endT > System.currentTimeMillis() / 1000) {
                            Toast.makeText(getApplicationContext(), "结束时间不能超过当天日期", Toast.LENGTH_SHORT).show();
                        } else {
                            map.put("collectTimeStart", mStartTime.getText().toString());
                            getHistoryByTime();
                        }
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        mEndTime.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (StringUtil.isNotEmpty(mStartTime.getText().toString()) && StringUtil.isNotEmpty(mEndTime.getText().toString())) {
                    if (!mStartTime.getText().toString().equals("请选择开始时间")) {
                        startT = dateUtils.getStringToDate(mStartTime.getText().toString(), "yyyy-MM-dd");
                        endT = dateUtils.getStringToDate(mEndTime.getText().toString(), "yyyy-MM-dd");
                        if (startT > endT) {
                            Toast.makeText(getApplicationContext(), "开始时间不能超过结束时间", Toast.LENGTH_SHORT).show();
                        } else if (endT > System.currentTimeMillis() / 1000) {
                            Toast.makeText(getApplicationContext(), "结束时间不能超过当天日期", Toast.LENGTH_SHORT).show();
                        } else {
                            map.put("collectTimeEnd", mEndTime.getText().toString());
                            getHistoryByTime();
                        }
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        mStartLayout.setOnClickListener(v -> {
            showDateAndTime(v.getContext(), 0);
        });

        mEndLayout.setOnClickListener(v -> {
            showDateAndTime(v.getContext(), 1);
        });
    }

    /**
     * 根据日期查记录
     */
    private void getHistoryByTime() {
        page = 1;
        map.put("isPage", true);
        map.put("pageIndex", page);
        map.put("pageSize", limit);
        Observable<BaseResponse<String>> observable = HttpRetrofitClient.getInstance().create(PublicService.class)
                .getHistory(Paper.book().read(Constants.TOKEN), map);
        HttpRetrofitClient.execute(observable, new ApiCall<String>() {
            @Override
            protected void success(String data) {
                if (StringUtil.isNotEmpty(data)) {
                    Log.i("医废追溯", data);
                    List<HistoryBean> list = JSONArray.parseArray(data, HistoryBean.class);
                    if (list != null && list.size() > 0) {
                        adapter = new HistoryAdapter(list);
                        mRvHistory.setAdapter(adapter);
                    } else {
                        mRvHistory.setAdapter(noDataAdapter);
                    }
                } else {
                    mRvHistory.setAdapter(noDataAdapter);
                }
            }
        });
    }

    /**
     * <Enter>
     * 显示全部日期
     *
     * @param context
     * @param type
     */
    @SuppressLint("ClickableViewAccessibility")
    public void showDateAndTime(final Context context, final int type) {
        Calendar c = Calendar.getInstance();
        int curYear = c.get(Calendar.YEAR);
        int curMonth = c.get(Calendar.MONTH) + 1;//通过Calendar算出的月数要+1
        int curDate = c.get(Calendar.DATE);

        final AlertDialog dialog = new AlertDialog.Builder(context).create();
        dialog.show();
        ImmersionBar.with(HistoryActivity.this, dialog).init();
        Window window = dialog.getWindow();
        // 设置布局
        window.setContentView(R.layout.date_time_picker_layout);
        window.setBackgroundDrawable(null);
        // 设置宽高
        window.setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        // 设置弹出的动画效果
        window.setWindowAnimations(R.style.AnimBottom);

        year = window.findViewById(R.id.new_year);
        initYear(context);
        month = window.findViewById(R.id.new_month);
        initMonth(context);
        day = window.findViewById(R.id.new_day);
        initDay(curYear, curMonth, context);

        // 设置当前时间
        year.setCurrentItem(curYear - 1950);
        month.setCurrentItem(curMonth - 1);
        day.setCurrentItem(curDate - 1);

        month.setVisibleItems(7);
        day.setVisibleItems(7);

        // 设置监听
        TextView ok = window.findViewById(R.id.set);
        TextView cancel = window.findViewById(R.id.cancel);
        ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String time = String.format(Locale.CHINA, "%04d-%02d-%02d", year.getCurrentItem() + 1950,
                        month.getCurrentItem() + 1, day.getCurrentItem() + 1);
                if (type == 0) {
                    mStartTime.setText(time);
                } else {
                    mEndTime.setText(time);
                }
                dialog.cancel();
            }
        });
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.cancel();
            }
        });
        LinearLayout root = window.findViewById(R.id.date_root);
        root.getBackground().setAlpha(0);
        LinearLayout cancelLayout = window.findViewById(R.id.view_none);
        cancelLayout.getBackground().setAlpha(0);
        cancelLayout.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                dialog.cancel();
                return false;
            }
        });
    }


    /**
     * <Enter>
     * 初始化年
     *
     * @param context
     */
    private void initYear(Context context) {
        NumericWheelAdapter numericWheelAdapter = new NumericWheelAdapter(context, 1950, 2050);
        numericWheelAdapter.setLabel(" 年");
        //		numericWheelAdapter.setTextSize(15);  设置字体大小
        year.setViewAdapter(numericWheelAdapter);
        year.setCyclic(true);
    }

    /**
     * <Enter>
     * 初始化月
     *
     * @param context
     */
    private void initMonth(Context context) {
        NumericWheelAdapter numericWheelAdapter = new NumericWheelAdapter(context, 1, 12, "%02d");
        numericWheelAdapter.setLabel(" 月");
        //		numericWheelAdapter.setTextSize(15);  设置字体大小
        month.setViewAdapter(numericWheelAdapter);
        month.setCyclic(true);
    }

    /**
     * <Enter>
     * 初始化天
     *
     * @param arg1
     * @param arg2
     * @param context
     */
    private void initDay(int arg1, int arg2, Context context) {
        NumericWheelAdapter numericWheelAdapter = new NumericWheelAdapter(context, 1, getDay(arg1, arg2), "%02d");
        numericWheelAdapter.setLabel(" 日");
        //		numericWheelAdapter.setTextSize(15);  设置字体大小
        day.setViewAdapter(numericWheelAdapter);
        day.setCyclic(true);
    }

    private int getDay(int year, int month) {
        int day = 30;
        boolean flag = false;
        switch (year % 4) {
            case 0:
                flag = true;
                break;
            default:
                flag = false;
                break;
        }
        switch (month) {
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
                day = 31;
                break;
            case 2:
                day = flag ? 29 : 28;
                break;
            default:
                day = 30;
                break;
        }
        return day;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //static的mInstance会保留之前弹出的筛选对话框的上下文，导致此Activity销毁时仍持有该context
        //所以此Activity销毁时置空筛选对话框，保证对话框拥有的静态上下文在下一次弹出时更新为最新的。
        FilterDialog.mInstance = null;
        //此Activity销毁时删去筛选对话框选中的记录
        Paper.book().delete(Constants.WASTE_CLASSIFY_CODE);
        Paper.book().delete(Constants.WASTE_STATUS);
        Paper.book().delete(Constants.HOSPITAL_DEPART_ID);
    }
}